package com.changhong.wlyspectrum.NewDesign;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.changhong.wlyspectrum.MainTestActivity.MainTestActivity;
import com.changhong.wlyspectrum.NetWork.HttpMethods;
import com.changhong.wlyspectrum.R;
import com.changhong.wlyspectrum.utils.Attributes;
import com.changhong.wlyspectrum.utils.CollectionAttri;
import com.changhong.wlyspectrum.utils.MyCollectionData;
import com.changhong.wlyspectrum.utils.MyEditText;
import com.google.gson.Gson;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Mr_tao
 * on 2017/4/11.
 */
public class AttributeActivity extends Activity implements View.OnClickListener{
    private final static String TAG = "AttributeActivity";
    private MyEditText edittext1 = null;
    private MyEditText edittext2 = null;
    private MyEditText edittext3 = null;

    private EditText medit_attribute_name = null;
    private EditText medit_attribute_unit = null;
    private EditText medit_attribute_descri = null;

    private TextView mtext_attribute_name = null;
    private TextView mtext_attribute_unit = null;
    private TextView mtext_attribute_descri = null;
    private ImageView mBackImv;

    private Button msave = null;
    private Button madd = null;
    private Button mUpdate;

    private ListView mlistview = null;

    private MyCollectionData mData = null;
    private List<Map<String, Object>> mlist = new ArrayList<Map<String, Object>>();
    private List<Attributes> attributesList = new ArrayList<Attributes>();
    private String user_id;
    private String token;
    private String flag;
    private String collectionId;

    private String[] mstring00 = {"单宁","",""};   //id = 12 高粱
    private String[] mstring01 = {"直链淀粉","",""};
    private String[] mstring02 = {"淀粉","",""};
    private String[] mstring03 = {"水分","",""};
    private String[] mstring04 = {"编号","",""};
    private String[] mstring05 = {"备注1","",""};
    private String[] mstring06 = {"备注2","",""};
    private String[] mstring07 = {"备注3","",""};

    private String[] mstring10 = {"水分","",""};  //id = 13 小麦
    private String[] mstring11 = {"淀粉","",""};
    private String[] mstring12 = {"编号","",""};
    private String[] mstring13 = {"备注1","",""};
    private String[] mstring14 = {"备注2","",""};
    private String[] mstring15 = {"备注3","",""};


    private String[] mstring20 = {"直链淀粉","",""};  //id = 14 糯米
    private String[] mstring21 = {"淀粉","",""};
    private String[] mstring22 = {"水分","",""};
    private String[] mstring23 = {"编号","",""};
    private String[] mstring24 = {"备注1","",""};
    private String[] mstring25 = {"备注2","",""};
    private String[] mstring26 = {"备注3","",""};

    private String[] mstring30 = {"淀粉","",""};  //id = 15 玉米
    private String[] mstring31 = {"脂肪酸值","",""};
    private String[] mstring32 = {"水分","",""};
    private String[] mstring33 = {"编号","",""};
    private String[] mstring34 = {"备注1","",""};
    private String[] mstring35 = {"备注2","",""};
    private String[] mstring36 = {"备注3","",""};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_attribute_layout);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar_attribute);

        InitData();
        InitUi();
    }
    private void InitData(){
        Intent intent = getIntent();
        flag = intent.getStringExtra("FLAG");
        Log.e(TAG,flag);
        if(flag.compareTo("1") == 0){
            mData = (MyCollectionData)intent.getSerializableExtra("MY_DATA");
        }else if(flag.compareTo("2") == 0){
            collectionId = intent.getStringExtra("collectionId");
            mData = (MyCollectionData)intent.getSerializableExtra("data");
        }


        SharedPreferences mypref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        user_id = mypref.getString("user_id", "default");
        token = mypref.getString("token", "default");
        Log.e(TAG,"user_id:" + user_id + "token:" + token);
    }

    private void InitUi(){
        mBackImv = (ImageView)findViewById(R.id.attribute2collection) ;
        mBackImv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        edittext1 = (MyEditText)findViewById(R.id.attribute_name);
        edittext2 = (MyEditText)findViewById(R.id.attribute_unit);
        edittext3 = (MyEditText)findViewById(R.id.attribute_descri);

        mtext_attribute_name = (TextView)edittext1.findViewById(R.id.my_name);
        medit_attribute_name = (EditText)edittext1.findViewById(R.id.my_descri);
        mtext_attribute_name.setText(getResources().getString(R.string.attribute_name));
        medit_attribute_name.setHint(getResources().getString(R.string.attribute_nameinput));

        mtext_attribute_unit = (TextView)edittext2.findViewById(R.id.my_name);
        medit_attribute_unit = (EditText)edittext2.findViewById(R.id.my_descri);
        mtext_attribute_unit.setText(getResources().getString(R.string.attribute_unit));
        medit_attribute_unit.setHint(getResources().getString(R.string.attribute_unitinput));

        mtext_attribute_descri = (TextView)edittext3.findViewById(R.id.my_name);
        medit_attribute_descri = (EditText)edittext3.findViewById(R.id.my_descri);
        mtext_attribute_descri.setText(getResources().getString(R.string.attribute_descri));
        medit_attribute_descri.setHint(getResources().getString(R.string.attribute_descriinput));

        mlistview = (ListView)findViewById(R.id.mList);

        msave = (Button)findViewById(R.id.save);
        madd = (Button)findViewById(R.id.add);
        mUpdate = (Button)findViewById(R.id.finish_create);
        msave.setOnClickListener(this);
        madd.setOnClickListener(this);
        mUpdate.setOnClickListener(this);
        mUpdate.setEnabled(false);
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.save:
                Log.e(TAG, "mData：" + "lct");
                String a_name = medit_attribute_name.getText().toString();
                if (!TextUtils.isEmpty(a_name)) {
                    String a_unnit = medit_attribute_unit.getText().toString();
                    String a_descri = medit_attribute_descri.getText().toString();
                    String mattribute = "name:" + a_name + "," + "unit:" + a_unnit + "," + "desciption:" + a_descri;

                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("name", a_name);
                    map.put("unit", a_unnit);
                    map.put("des", a_descri);
                    mlist.add(map);

                    Attributes attributes = new Attributes();
                    attributes.setName(a_name);
                    attributes.setUnit(a_unnit);
                    attributes.setDescription(a_descri);
                    attributesList.add(attributes);

                    SimpleAdapter adapter = new SimpleAdapter(this, mlist, R.layout.collection_list_item, new String[]{"name", "unit", "des"}, new int[]{R.id.m_name, R.id.m_unit, R.id.m_des});
                    mlistview.setAdapter(adapter);
                    mlistview.invalidate();
                    mData.setAttribute(attributesList);
                    mUpdate.setEnabled(true);
                } else {
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.isnull), Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.add:
                medit_attribute_name.setText("");
                medit_attribute_unit.setText("");
                medit_attribute_descri.setText("");

                /*mAttributeAdd("12",putString12());
                mAttributeAdd("13",putString13());
                mAttributeAdd("14",putString14());
                mAttributeAdd("15",putString15());*/

                break;
            case R.id.finish_create:
                String name = mData.getName();
                String descri = mData.getDescri();
                List<Attributes> attr_list = mData.getAttribute();
                JSONArray jsonArray = new JSONArray();
                JSONObject tmpObj = null;
                int count = attr_list.size();
                for(int i = 0;i < count; i++){
                    tmpObj = new JSONObject();
                    try {
                        tmpObj.put("name",attr_list.get(i).name);
                        tmpObj.put("unit",attr_list.get(i).unit);
                        tmpObj.put("description",attr_list.get(i).description);
                        jsonArray.put(tmpObj);
                        tmpObj = null;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                String collectionAttri = jsonArray.toString();
                Log.e(TAG,"name-->" + name + "desc-->" + descri + "attri-->" + collectionAttri );
                if(flag.compareTo("1") == 0){
                    UpdateCollection(name,descri,collectionAttri);
                }else if(flag.compareTo("2") == 0){
                    modifyAttributes(collectionId,collectionAttri);
                }
                //UpdateCollection(name,descri,collectionAttri);
                break;
        }
    }

    private Handler AttriHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    Toast.makeText(getApplicationContext(), R.string.collection_success, Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(AttributeActivity.this, HomeActivity.class);
                    startActivity(intent);
                    break;
                case 1:
                    Toast.makeText(getApplicationContext(), R.string.collection_fail, Toast.LENGTH_LONG).show();
                    break;
                case 2:
                    Toast.makeText(getApplicationContext(),getString(R.string.modify_success),Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case 3:
                    Toast.makeText(getApplicationContext(),getString(R.string.modify_fail),Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case 98:
                    Toast.makeText(getApplicationContext(), R.string.service_error, Toast.LENGTH_LONG).show();
                    break;
                case 99:
                    Toast.makeText(getApplicationContext(), R.string.network_error, Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        }
    };
    private void UpdateCollection(final String name, final String description, final String collection){
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    JSONObject js = new JSONObject();
                    try {
                        js.put("name",name);
                        js.put("description",description);
                        js.put("attributesTemplate",collection);
                        //Response response = HttpMethods.UpdateCollectionData("/collection/new",token,user_id,name,description,collection);
                        Response response = HttpMethods.NewResponse("/collection/new",user_id,token,js.toString());
                        if(response.isSuccessful()){
                            String result = response.body().string();
                            Log.e(TAG,"result----->" + result);
                            JSONObject jsonObject = new JSONObject(result);
                            String code = jsonObject.getString("code");
                            if(code.compareTo("0") == 0){
                                AttriHandler.sendMessage(Message.obtain(AttriHandler, 0));
                            }else{
                                AttriHandler.sendMessage(Message.obtain(AttriHandler, 1));
                            }
                        }else{
                            AttriHandler.sendMessage(Message.obtain(AttriHandler, 99));
                        }
                    } catch (IOException e) {
                        AttriHandler.sendMessage(Message.obtain(AttriHandler, 99));
                        e.printStackTrace();
                    } catch (JSONException e) {
                        AttriHandler.sendMessage(Message.obtain(AttriHandler, 99));
                        e.printStackTrace();
                    }
                }
            }.start();
    }

    private void modifyAttributes(final String collectionId, final String attributeTemplate){
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    JSONObject js = new JSONObject();
                    try {
                        js.put("collectionId",collectionId);
                        js.put("attributesTemplate",attributeTemplate);
                        Response response = HttpMethods.NewResponse("/collection/modifyAttributes",user_id,token,js.toString());
                        if(response.isSuccessful()){
                            String result = response.body().string();
                            Log.e(TAG,"result----->" + result);
                            JSONObject jsonObject = new JSONObject(result);
                            String code = jsonObject.getString("code");
                            if(code.compareTo("0") == 0){
                                AttriHandler.sendMessage(Message.obtain(AttriHandler, 0));
                            }else{
                                AttriHandler.sendMessage(Message.obtain(AttriHandler, 1));
                            }
                        }else{
                            AttriHandler.sendMessage(Message.obtain(AttriHandler, 99));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
    }

    private List<String[]> putString12(){
        List<String[]> mlist = new ArrayList<>();
        mlist.add(mstring00);
        mlist.add(mstring01);
        mlist.add(mstring02);
        mlist.add(mstring03);
        mlist.add(mstring04);
        mlist.add(mstring05);
        mlist.add(mstring06);
        mlist.add(mstring07);
        return mlist;
    }

    private List<String[]> putString13(){
        List<String[]> mlist = new ArrayList<>();
        mlist.add(mstring10);
        mlist.add(mstring11);
        mlist.add(mstring12);
        mlist.add(mstring13);
        mlist.add(mstring14);
        mlist.add(mstring15);
        return mlist;
    }

    private List<String[]> putString14(){
        List<String[]> mlist = new ArrayList<>();
        mlist.add(mstring20);
        mlist.add(mstring21);
        mlist.add(mstring22);
        mlist.add(mstring23);
        mlist.add(mstring24);
        mlist.add(mstring25);
        mlist.add(mstring26);
        return mlist;
    }
    private List<String[]> putString15(){
        List<String[]> mlist = new ArrayList<>();
        mlist.add(mstring30);
        mlist.add(mstring31);
        mlist.add(mstring32);
        mlist.add(mstring33);
        mlist.add(mstring34);
        mlist.add(mstring35);
        mlist.add(mstring36);
        return mlist;
    }

    private void mAttributeAdd(String collectionId,List<String[]> mlist){
        JSONArray jsonArray = new JSONArray();
        JSONObject tmpObj = null;
        int count = mlist.size();
        for(int i = 0;i < count; i++){
            tmpObj = new JSONObject();
            try {
                tmpObj.put("name",mlist.get(i)[0]);
                tmpObj.put("unit",mlist.get(i)[1]);
                tmpObj.put("description",mlist.get(i)[2]);
                jsonArray.put(tmpObj);
                tmpObj = null;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        String collectionAttri = jsonArray.toString();
        modifyAttributes(collectionId,collectionAttri);
    }
}
